<template>
  <div class="project">
    <!-- 代码橱窗-项目详情页 {{ route.params.id }} -->
    <div class="content">
      <!-- // 左侧文章部分 -->
      <div class="left">
        <!-- 页头 -->
        <div class="page-header">
          <el-page-header :icon="ArrowLeft" @back="handleBack">
            <template #title>
              <span>返回</span>
            </template>
            <template #content>
              <span class="text-large font-600 mr-3"> 项目详情 </span>
            </template>
          </el-page-header>
        </div>
        <!-- 项目标题 -->
        <h2 class="title">{{ projectInfo.pro_title }}</h2>
        <div class="tag-list">
          <ul>
            <div>类目:</div>
            <li class="tag" v-for="item, index of projectInfo.tags">{{ item }}</li>
          </ul>
        </div>
        <main>
          <!-- 项目背景 -->
          <div class="context">
            <!-- 背景 -->
            <div class="context-title">代码背景/简介</div>
            <div class="context-text">
              <p>{{ projectInfo.pro_biography }}</p>
              <!-- 封面图片 -->
              <div>
                <el-image style="width: 200px; height: 200px" v-if="projectInfo.pro_cover"
                  :src="'http://127.0.0.1:3000/uploads/' + projectInfo.pro_cover" fit="fill" />
              </div>
            </div>
          </div>

          <!-- 项目介绍 -->
          <div class="introduce">
            <div class="introduce-title">代码介绍</div>
            <p v-html="projectInfo.pro_content"></p>
            <!-- 项目图片列表 -->
            <el-image style="width: 100px; height: 100px" :src="item.url" fit="fill"
              v-for="item, index of projectInfo.picUrlList" :key="item.id" />
          </div>
          <!-- 项目价格 -->
          <div class="money">
            <div class="money-title">项目价格</div>
            <p v-if="projectInfo.price === 0">
              免费项目: <span style="color: #ff6d02;">{{ projectInfo.price }}</span> 币
            </p>
            <p v-else>
              付费项目: <span style="color: #ff6d02;">{{ projectInfo.price }}</span> 币
            </p>
          </div>
          <!-- 对项目的操作 购买/收藏/下载 -->
          <el-divider />
          <div class="btnList">
            <el-button type="primary" round @click="dialogVisible = true">购买</el-button>
            <el-button type="info" round @click="handleCollection">收藏</el-button>
            <el-button type="success" round @click="handleDownload">下载</el-button>
            <el-dialog v-model="dialogVisible" title="订单信息" width="30%">
              <div class="money">
                <div class="money-title">项目名称</div>
                <div>
                  <p>
                    {{ projectInfo.pro_title }}
                  </p>
                </div>
                <div class="money-title">项目价格</div>
                <p v-if="projectInfo.price === 0">
                  免费项目: <span style="color: #ff6d02;">{{ projectInfo.price }}</span> 币
                </p>
                <p v-else>
                  付费项目: <span style="color: #ff6d02;">{{ projectInfo.price }}</span> 币
                </p>
                <div class="money-title">账户余额</div>
                <p>
                  <span style="color: #ff6d02;">{{ orders_userinfo.money }}</span> 币
                </p>
                <div style="padding-top: 20px;">
                  注意：数字虚拟商品一经购买，便永久绑定您的账号，<b>不支持任何理由的退款</b>。
                </div>
              </div>
              <template #footer>
                <span class="dialog-footer">
                  <el-button @click="dialogVisible = false">取消</el-button>
                  <el-button type="success" @click="handleToBuy">
                    购买
                  </el-button>
                </span>
              </template>
            </el-dialog>
          </div>
        </main>
      </div>
      <!-- // 右侧用户信息部分 -->
      <div class="right">
        <div class="user-info">
          <UserInfo :showAuthor="true" :targetUserId="targetUserId" />
        </div>
      </div>
      <!-- 评论区 -->
      <div class="comment" v-if="true">
        <Comments></Comments>
      </div>
    </div>

  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, nextTick } from "vue"
import { useRoute, useRouter } from 'vue-router'
import UserInfo from '@/components/UserInfo/index.vue'
import Comments from './components/Comments/index.vue'
import Service from '@/utils/axios'
import { ArrowLeft } from '@element-plus/icons-vue'
import userInfoI from '@/views/CodeTrade/types'
import { ElMessage, ElMessageBox } from "element-plus";
import "element-plus/es/components/message/style/css"; // 按需引入ElMessage样式失败，手动引入
import "element-plus/es/components/message-box/style/css";
//pinia
import { useUserStore } from "@/store/user";
const userStore = useUserStore();

// 模态框
const dialogVisible = ref(false)

// 订单信息
const orders_userinfo = ref<any>({});

// 路由
const route = useRoute();
const router = useRouter();
console.log(route.params.id)
const handleBack = () => {
  router.back();
}

let projectInfo = reactive<any>({})
let targetUserId = '';

// 请求项目详情数据
const getProjectDetail = async () => {
  await Service.post('/bkapi/projectInfo/getProjectinfoById', {
    id: route.params.id,
  })
    .then(res => {
      // projectInfo = res?.data?.data?.data
      Object.assign(projectInfo, res?.data?.data)
      console.log(projectInfo)
      console.log(res?.data)
      // projectInfo.tags = projectInfo.tags == '' ? '' : projectInfo.tags.split(',')
      projectInfo.tags = JSON.parse(projectInfo.tags);
      targetUserId = projectInfo.users_model.username;
      console.log('targetUserId', targetUserId)
      // projectTitle = res?.data?.data?.projectTitle;
      // coverUrl = res?.data?.data?.coverUrl;
      // projectTagList = res?.data?.data?.projectTagList;
      // projectContext = 
    })
}
// 获取项目详情
getProjectDetail();

// 确认购买方法
const handleToBuy = () => {
  ElMessageBox.confirm(
    '你确定要购买该项目吗？',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      if (orders_userinfo.value.money < projectInfo.price) {
        ElMessageBox.confirm(
          '账户余额不足!购买失败。',
          '警告',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            cancelButtonClass: 'display',
            type: 'warning',
          }
        )
          .then(() => {
          })
          .catch(() => {
          })
      } else {
        handleBuy();
      }
    })
    .catch(() => {
      // catch error
    })
}
// 购买方法
const handleBuy = () => {
  console.log('购买')
  Service.post('/bkapi/projectBuyInfo/postProIdToBuy', {
    proId: projectInfo.pro_id,
    userInfo: JSON.stringify({
      userId: localStorage.getItem('userid'),
      username: localStorage.getItem('username'),
    })
  })
    .then((res: any) => {
      console.log('res', res.data)
      if (res.data.status === 200 && res.data?.data.user_id === localStorage.getItem('userid')) {
        ElMessage({
          showClose: true,
          message: '购买成功!',
          type: 'success',
        })
        dialogVisible.value = true;
        Service.get('/bkapi/userinfo/getUserinfoByUsername', {
          params: {
            username: localStorage.getItem('username'),
          }
        }).then((res2: any) => {
          if (res2.data.status === 200) {
            userStore.setAvatarUrl(res2.data.data.user_pic);
            userStore.setUserInfo(JSON.stringify(res2.data.data));
            userStore.setUserId(res2.data.data.user_id)
          }
        })
      } else {
        ElMessage({
          showClose: true,
          message: res.data?.message,
          type: 'error',
        })
      }
    })
}
// 收藏方法
const handleCollection = () => {
  console.log('收藏')
}
// 下载方法
const handleDownload = () => {
  console.log('下载')
  Service.post('/bkapi/projectBuyInfo/postProIdUserIdToBy', {
    proId: projectInfo.pro_id,
    userId: localStorage.getItem('userid'),
  })
    .then((res: any) => {
      console.log('BuyInfores', res)
      if (res.data?.data) {
        if (res.data?.data.pro_id === projectInfo.pro_id) {
          ElMessage({
            showClose: true,
            message: '开始下载',
            type: 'success',
          })
        }
      } else {
        ElMessage({
          showClose: true,
          message: '未购买，请购买后下载!',
          type: 'error',
        })
      }
    })
}

onMounted(() => {
  orders_userinfo.value = JSON.parse(localStorage.getItem('userinfo') as string);
  // console.log('orders_userinfo.value',orders_userinfo.value);
})

</script>

<style lang="less" scoped>
@border-color: #dcdfe6; //边框默认颜色

.display {
  display: none;
}

.project {
  margin-top: 30px;

  .content {
    display: grid;
    grid-template-columns: 3fr 1fr;
    column-gap: 1rem;

    .left {
      padding: 50px 60px 10px 60px;
      background-color: #fff;
      border-radius: 10px;
      box-shadow: 0 10px 10px 5px rgba(0, 0, 0, .1);
      position: relative;

      .page-header {
        position: absolute;
        top: 10px;
        left: 10px;
      }

      h2 {
        font-size: 22px;
        // border-left: 4px solid #ff6d02;
        // padding-left: 15px;
      }

      .tag-list {
        padding-top: 20px;
        color: #999999;

        ul {
          display: flex;
          justify-content: flex-start;
          font-size: 16px;

          div:first-child {
            padding-right: 10px;
          }

          li {
            position: relative;
            padding: 0 10px;
            font-size: 16px;

            &:not(:last-child)::after {
              position: absolute;
              right: -4px;
              content: "/";

            }
          }


        }
      }

      main {

        .context {

          .context-title {
            margin-top: 20px;
            border-left: 4px solid #ff6d02;
            padding-left: 8px;
            font-size: 18px;
          }

          .context-text {
            display: grid;
            grid-template-columns: 3fr 1fr;
            column-gap: 1rem;

            &>p {
              margin-top: 20px;
              padding: 20px;
              background: hsla(0, 0%, 78%, .3);
              border: 1px solid #c4c4c4;
              border-radius: 2px;
              color: #999;
              line-height: 28px;
              margin-bottom: 8px;
              font-size: 14px;
            }

            &>div {
              margin-top: 20px;
            }
          }
        }

        .introduce {

          .introduce-title {
            margin-top: 20px;
            border-left: 4px solid #ff6d02;
            padding-left: 8px;
            font-size: 18px;
          }

          p {
            margin-top: 20px;
            padding: 20px;
            background-color: #fff;
            border: 1px solid @border-color;
            border-radius: 10px;
          }
        }

        .money {

          .money-title {
            margin-top: 20px;
            border-left: 4px solid #ff6d02;
            padding-left: 8px;
            font-size: 18px;
          }

          p {
            padding-top: 20px;
            font-size: 20px;
            font-weight: 700;
          }
        }

        .btnList {
          padding: 10px 20px 20px 20px;

          display: flex;
          justify-content: center;
          align-items: center;
        }

      }
    }

    // .right {}

    .comment {
      margin-top: 20px;
      padding: 20px;
      background-color: #fff;
      border: 1px solid @border-color;
      border-radius: 10px;
      box-shadow: 0 10px 10px 5px rgba(0, 0, 0, .1);
    }
  }


}
</style>
<style lang="less">
@border-color: #dcdfe6; //边框默认颜色

p {
  img {
    display: block;
    width: 50%;
    margin: 0 auto;
    background-color: #fff;
    border: 1px solid @border-color;
    border-radius: 10px;
    box-shadow: 0 10px 10px 5px rgba(0, 0, 0, .1);
  }
}
</style>